const chalk = require('chalk');
const { program } = require('commander');
const dartGen = require('../package.json');
const alphaGenerate = require('./index.js');
const fetch = require('./utils/request.js');
const loadContent = require('./utils/local.js');
const handle = require('./utils/handle.js');

program.name(dartGen.name).version(dartGen.version);
program
  .option('-o, --out <file>', 'output filename')
  .option('-d, --dir <path>', 'output dirname')
  .option('-c, --class <className>', 'output className')
  .option('--url <url>', 'input json schema from the url')

async function command () {
  program.parse(process.argv);
  const options = program.opts();

  try {
    if (program.args.length) {
      for (const file of program.args) {
        const data = await loadContent(file);
        handle(alphaGenerate(data, options.class), options);
      }
    } else if (options.url) {
      const data = await fetch(options.url);
      handle(alphaGenerate(data, options.class), options);
    } else {
      console.log(chalk.yellow('请通过 dartGen --help，查看必要参数并传入'));
    }
  } catch (error) {
    console.log(chalk.red(error));
  }
}

command().catch((err) => {
  console.error(err.stack ?? err);
});
